<script type="text/javascript">
Ext.BLANK_IMAGE_URL = 'assets/images/s.gif';

Docs = {};
Docs.icons = {"Icons":"icon-frm"};

ApiPanel = function() {
	// call parent constructor
	// ApiPanel.superclass.constructor.call(this, el, config);
    ApiPanel.superclass.constructor.call(this, {
        id:'api-tree',
        region:'west',
        title:'Application Menus',
        split:true,
        width: 220,
        minSize: 220,
        maxSize: 300,
        collapsible: true,
        margins:'0 0 5 5',
        cmargins:'0 0 0 0',
        rootVisible:true,
        lines:false,
        autoScroll:true,
        animCollapse:true,
        animate: true,
        //collapseMode:'mini',
        loader: new Ext.tree.TreeLoader({
			//preloadChildren: true,
			//clearOnLoad: false
			//dataUrl:'index.php?c=main&m=get_tree_asset'
		}),
        root: new Ext.tree.AsyncTreeNode({
            text:'All',
            id:'root',
            expanded:true,
            iconCls: 'icon-docs'
            //, children:[Docs.classData]
         }),
        collapseFirst:false
    });
    // no longer needed!

    this.getSelectionModel().on('beforeselect', function(sm, node){
        return node.isLeaf();
    });
};

Ext.extend(ApiPanel, Ext.tree.TreePanel, {
    selectClass : function(cls){
        if(cls){
            var parts = cls.split('.');
            var last = parts.length-1;
            for(var i = 0; i < last; i++) {
                var p = parts[i];
                var fc = p.charAt(0);
                var staticCls = fc.toUpperCase() == fc;
                if(p == 'Ext' || !staticCls){
                    parts[i] = 'pkg-'+p;
                }else if(staticCls){
                    --last;
                    parts.splice(i, 1);
                }
            }
            parts[last] = cls;

            this.selectPath('/root/'+parts.join('/'));
        }
    },

	selectClassUsingPath : function(path){
        if(path){
            this.selectPath( path );
        }
    }
});


DocPanel = Ext.extend(Ext.Panel, {
    closable: false,
    autoScroll:true,

    initComponent : function(){
        var ps = this.cclass.split('.');
        this.title = ps[ps.length-1];

        DocPanel.superclass.initComponent.call(this);
    },

    scrollToMember : function(member){
        var el = Ext.fly(this.cclass + '-' + member);
        if(el){
            var top = (el.getOffsetsTo(this.body)[1]) + this.body.dom.scrollTop;
            this.body.scrollTo('top', top-25, {duration:.75, callback: this.hlMember.createDelegate(this, [member])});
        }
    },

	scrollToSection : function(id){
		var el = Ext.getDom(id);
		if(el){
			var top = (Ext.fly(el).getOffsetsTo(this.body)[1]) + this.body.dom.scrollTop;
			this.body.scrollTo('top', top-25, {duration:.5, callback: function(){
                Ext.fly(el).next('h2').pause(.2).highlight('#8DB2E3', {attr:'color'});
            }});
        }
	},

    hlMember : function(member){
        var el = Ext.fly(this.cclass + '-' + member);
        if(el){
            el.up('tr').highlight('#cadaf9');
        }
    }
});


MainPanel = function() {
    MainPanel.superclass.constructor.call(this, {
        id:'doc-body',
        region:'center',
        margins:'0 0 0 0',
        resizeTabs: true,
        minTabWidth: 200,
        tabWidth: 200,
        plugins: new Ext.ux.TabCloseMenu(),
        enableTabScroll: true,
        activeTab: 0,
        items: {
            id:'welcome-panel',
            title: 'Welcome Home',
            style: 'background: url(assets/images/desktop.jpg)',
            autoLoad: {url: 'index.php?c=c_welcome', scripts: true},
            iconCls:'icon-docs',
            autoScroll: true
        }
    });
};

Ext.extend(MainPanel, Ext.TabPanel, {
    initEvents : function(){
        MainPanel.superclass.initEvents.call(this);
        this.body.on('click', this.onClick, this);
    },

    onClick: function(e, target){
        if(target == e.getTarget('a:not(.exi)', 3)){
            var cls = Ext.fly(target).getAttributeNS('ext', 'cls');
            e.stopEvent();
            if(cls){
                var member = Ext.fly(target).getAttributeNS('ext', 'member');
                this.loadClass(target.href, cls, member);
            }else if(target.className == 'inner-link'){
                this.getActiveTab().scrollToSection(target.href.split('#')[1]);
            }else{
                window.open(target.href);
            }
        }else if(target == e.getTarget('.micon', 2)){
            e.stopEvent();
            var tr = Ext.fly(target.parentNode);
            if(tr.hasClass('expandable')){
                tr.toggleClass('expanded');
            }
        }
    },

    loadClass : function(href, cls, member){
        var id = 'docs-' + cls;
        var tab = this.getComponent(id);
        if(tab){
            this.setActiveTab(tab);
            if(member){
                tab.scrollToMember(member);
            }
        }else{
            var autoLoad = {url: href, scripts: true};
            if(member){
                autoLoad.callback = function(){
                    Ext.getCmp(id).scrollToMember(member);
                }
            }
            var p = this.add(new DocPanel({
                id: id,
                cclass : cls,
                autoLoad: autoLoad,
				style: 'background: url(assets/images/desktop.jpg)',
                iconCls: Docs.icons[cls]
            }));
            this.setActiveTab(p);
        }
    }
});

var mainPanel = new MainPanel();

Ext.onReady( function() {
    Ext.QuickTips.init();

    var api = new ApiPanel();

	var menupanel= new Ext.TabPanel({
        deferredRender: false,
        activeTab: 0,     // first tab initially active
        height: 120,
        tabWidth: 200,
        items: [
           <?php $m=0; foreach($menus as $listmenus){ $m++; ?>
            {
            title: '<?php echo $listmenus["menu_title"]; ?>',
            autoScroll: true,
			baseCls: 'x-tab-bg',
            tbar: [
                   <?php $g=0; foreach($subgroups as $listsubgroups) { $g++;?>
                   <?php if($listsubgroups["menu_parent"]==$listmenus["menu_id"]){?>
            	   {
					xtype: 'buttongroup',
					title: '<?php echo $listsubgroups["menu_group"]; ?>',
					defaults: {
						scale: 'medium'
					},
					items: [
						<?php $s=0; foreach($submenus as $listsubmenus){ $s++; ?>
						<?php if($listsubmenus["menu_parent"]==$listmenus["menu_id"]
								 && $listsubmenus["menu_group"]==$listsubgroups["menu_group"]){?>
						{
							text: '<?php echo "<center>".$listsubmenus["menu_title"]."</center>"; ?>',
							iconCls: '<?php echo 'icon-'.$listsubmenus["menu_id"]; ?>',
							arrowAlign : 'top',
							minWidth: 50,
							width: 50,
							iconAlign: 'top',
							handler: function() {
								mainPanel.remove(mainPanel.getActiveTab().getId());
								mainPanel.loadClass('<?php echo (trim($listsubmenus["menu_link"])<>""?$listsubmenus["menu_link"]:'errorlink');?>', '<?php echo strip_tags(ereg_replace('<br/>', ' ', $listsubmenus["menu_title"])); ?>');
							}
						}
						<?php if($s<count($submenus)){ ?>,<?php } ?>
						<?php } ?>
						<?php } ?>
					]
				 }
            	<?php if($g<count($subgroups)){ ?>,<?php } ?>
 				<?php } ?>
				<?php } ?>
      			]
        	}
        	<?php if($m<count($menus)){ ?>,<?php } ?>
       		<?php } ?>
        ]
    });

    var headerPanel={
            // lazily created panel (xtype:'panel' is default)
            region: 'north',
            split: true,
            autoHeight: true,
            minSize: 100,
            maxSize: 200,
            collapsible: false,
            margins: '0 0 0 0',
            items:[
                new Ext.BoxComponent({
                    region: 'north',
					el:'header',
					height: 32, // give north and south regions a height
					anchor: 'none -25'
                }),menupanel
            ]
        }
    var viewport = new Ext.Viewport({
        layout:'border',
        //items:[ hd, api, mainPanel ]
        items:[headerPanel, mainPanel ]
    });

    //api.expandPath('/root/apidocs');

    // allow for link in
    var page = window.location.href.split('?')[1];
    if(page){
        var ps = Ext.urlDecode(page);
        var cls = ps['class'];
		if(cls) {
        mainPanel.loadClass('index.php?c=' + cls + '', cls, ps.member);
		}
    }

    viewport.doLayout();

	setTimeout(function(){
        Ext.get('loading').remove();
        Ext.get('loading-mask').fadeOut({remove:true});
    }, 250);

	var filter = new Ext.tree.TreeFilter(api, {
		clearBlank: true,
		autoClear: true
	});
	var hiddenPkgs = [];
	function filterTree(e){
		var text = e.target.value;
		Ext.each(hiddenPkgs, function(n){
			n.ui.show();
		});
		if(!text){
			filter.clear();
			return;
		}
		api.expandAll();

		var re = new RegExp('^' + Ext.escapeRe(text), 'i');
		filter.filterBy(function(n){
			return !n.attributes.isClass || re.test(n.text);
		});

		// hide empty packages that weren't filtered
		hiddenPkgs = [];
		api.root.cascade(function(n){
			if(!n.attributes.isClass && n.ui.ctNode.offsetHeight < 3){
				n.ui.hide();
				hiddenPkgs.push(n);
			}
		});
	}
});
</script>